package com.xuecheng.config;

import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

@Slf4j
@Configuration
public class MultipartSupportConfig {
	
	@Resource
	private ObjectFactory<HttpMessageConverters> messageConverters;
	
	//将file转为Multipart
	public static MultipartFile getMultipartFile(File file) {
		FileItem item = new DiskFileItemFactory().createItem("file", MediaType.MULTIPART_FORM_DATA_VALUE, true,
      file.getName());
		try (FileInputStream inputStream = new FileInputStream(file);
		     OutputStream outputStream = item.getOutputStream();) {
			IOUtils.copy(inputStream, outputStream);
			
		} catch (Exception e) {
			log.error("文件上传失败:{}", e.getMessage());
		}
		return new CommonsMultipartFile(item);
	}
	
	@Bean
	@Primary//注入相同类型的bean时优先使用
	@Scope("prototype")
	public Encoder feignEncoder() {
		return new SpringFormEncoder(new SpringEncoder(messageConverters));
	}
}
